package com.jingdun.sport.api.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jingdun.sport.authority.SecurityChecker;
import com.jingdun.sport.bean.model.*;
import com.jingdun.sport.common.constants.RedisConstants;
import com.jingdun.sport.common.util.DateUtil;
import com.jingdun.sport.security.util.SecurityUtils;
import com.jingdun.sport.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/sport/roomUserRelation/")
@Api(tags = "活动室用户关联关系接口")
public class RoomUserRelationController {

    @Autowired
    private RoomUserRelationService roomUserRelationService;

    @Autowired
    private SportRecordService sportRecordService;

    @Autowired
    private SecurityChecker securityChecker;

    @Autowired
    private RoomService roomService;

    @Autowired
    private UserService userService;

    @Autowired
    private SportConfigService sportConfigService;

    @Autowired
    RoomUserSportRecordPerDayService roomUserSportRecordPerDayService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 加入活动室接口
     */
    @PostMapping("/joinRoom")
    @ApiOperation(value = "加入活动室", notes = "加入活动室")
    public ResponseEntity<ApiResult> joinRoom(@RequestBody RoomUserRelation roomUserRelation) {
        ApiResult apiResult = new ApiResult();

        //一个房间中, 同一个人不能出现两次
        Map m = new HashMap<String, Object>();
        m.put("roomId", roomUserRelation.getRoomId());
        m.put("userId", roomUserRelation.getUserId());
        RoomUserRelation r = roomUserRelationService.getRoomUserRelationDetail(m);
        if (null != r) {
            apiResult.setMsg("一个房间中同一个人不能出现两次");
            return ResponseEntity.ok(apiResult);
        }


        m = new HashMap<String, Object>();
        m.put("id", roomUserRelation.getRoomId());
        Room room = roomService.getRoomDetail(m);
        if (room.getPassword() != null && !roomUserRelation.getPassword().equals(room.getPassword())) {
            apiResult.setMsg("房间密码错误，请重新输入。");
            apiResult.setCode(201);
            return ResponseEntity.ok(apiResult);
        }

        //判断是否过了开始时间, 如果已经过了, 就不让加入活动室
        //行驶开始时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long beginDateLong = -1;
        try {
            beginDateLong = sdf.parse(room.getBeginDate()).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long nowLong = -1;
        Date nowDate = new Date();
        try {
            nowLong = sdf.parse(sdf.format(nowDate)).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (nowLong > beginDateLong) {
            apiResult.setMsg("过了开始时间" + room.getBeginDate() + ", 不能加入活动室");
            return ResponseEntity.ok(apiResult);
        }

        //奖励类型为押金的时候, 才计算累计押金
        if (room.getPrizeType() != 1) {
            roomUserRelation.setUserId(securityChecker.getUser().getUserId());
            roomUserRelationService.addRoomUserRelation(roomUserRelation);
        }
        redisTemplate.opsForSet().add(RedisConstants.StudyPageJoinPerson + room.getSportProject(), roomUserRelation.getUserId());
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 分页获取活动室用户关联关系接口
     */
    @RequestMapping("/getPaginationRoomUserRelation")
    @ApiOperation(value = "分页获取活动室用户关联关系接口", notes = "分页获取活动室用户关联关系接口")
    public ResponseEntity<ApiResult> getPaginationRoomUserRelation(long size, long current, String roomId) {
        Map m = new HashMap<String, Object>();
        m.put("size", size);
        m.put("current", current);
        m.put("roomId", roomId);
        Page<Map<String, Object>> page = roomUserRelationService.getPaginationRoomUserRelation(m);
        //return ResponseEntity.ok(page.getRecords());
        ApiResult apiResult = new ApiResult();
        apiResult.setData(page);
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 获取活动室排行榜第一名和最后一名接口
     */
    @GetMapping("/getRankFirstAndRankLastList")
    @ApiOperation(value = "获取活动室排行榜第一名和最后一名接口", notes = "获取活动室排行榜第一名和最后一名接口")
    public ResponseEntity<ApiResult> getRankFirstAndRankLastList(long roomId) {
        Map m = new HashMap<String, Object>();
        m.put("id", roomId);
        m.put("roomId", roomId);
        Room room = roomService.getRoomDetail(m);
        QueryWrapper<RoomUserRelation> roomWraper = new QueryWrapper<>();
        roomWraper.eq("room_id", roomId);
        roomWraper.eq("all_done", 1);
        List<RoomUserRelation> list = roomUserRelationService.list(roomWraper);
        long activity = 0;
        //统计每个用户的打卡记录数据,放入hashmap
        Map m2 = new HashMap<String, Object>();
        HashMap<String, Integer> t = new HashMap<>();
        User user = null;
        for (int i = 0; i < list.size(); i++) {
            RoomUserRelation rl = list.get(i);
            QueryWrapper<RoomUserSportRecordPerDay> rusrpdWrapper = new QueryWrapper<>();
            rusrpdWrapper.eq("room_id", roomId).eq("user_id", rl.getUserId());
            Integer c = roomUserSportRecordPerDayService.count(rusrpdWrapper);
            user = userService.getById(rl.getUserId());
            t.put(user.getUserId(), c);
        }
        LinkedHashMap<String, Integer> sortedMap = t.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors
                        .toMap(Map.Entry::getKey,
                                Map.Entry::getValue,
                                (e1, e2) -> e1,
                                LinkedHashMap::new));
        Set<String> keySet = sortedMap.keySet();
        Iterator<String> it1 = keySet.iterator();
        ArrayList<String> users = new ArrayList();
        String roomIds = null;
        while (it1.hasNext()) {
            String ID = it1.next();
            Integer stu = sortedMap.get(ID);
            System.out.println(ID + " " + stu);
            //users.add(ID);
            QueryWrapper<SportRecord> sportRecord = new QueryWrapper<>();
            sportRecord.eq("user", ID);
            List<SportRecord> list2 = new ArrayList<>();
            try {
                list2 = sportRecordService.list(sportRecord);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String status;
            String RealName = null;
            String[] a = new String[5];
            long activity2 = 0;
            int aa = 0;
            boolean bl = false;
            System.out.println("ID是:" + ID);
            user = userService.getById(ID);
            if (user != null) {
                RealName = user.getRealName();
            }
            for (SportRecord sl : list2) {
                status = sl.getStatus();
                if (status.equals("1") && room.getId().equals(roomId)) {
                    users.add(RealName);
                    break;
                }
            }
        }
        //排序,并倒排放入list中
        Collections.reverse(users);


        //return

        ApiResult apiResult = new ApiResult();
        apiResult.setData(users);
        return ResponseEntity.ok(apiResult);
    }

//    /**
//     * 获取活动室排行榜第一名和最后一名接口
//     */
//    @GetMapping("/getRankFirstAndRankLastList")
//    @ApiOperation(value = "获取活动室排行榜第一名和最后一名接口", notes = "获取活动室排行榜第一名和最后一名接口")
//    public ResponseEntity <ApiResult> getRankFirstAndRankLastList(long roomId) {
//        Map m = new HashMap<String, Object>();
//        m.put("roomId", roomId);
//        List list = roomUserRelationService.getRankFirstAndRankLastList(m);
//        ApiResult apiResult = new ApiResult();
//        apiResult.setData(list);
//        return ResponseEntity.ok(apiResult);
//    }

    /**
     * 分页获取全民运动接口
     */
    @RequestMapping("/getPaginationAllPeopleSport")
    @ApiOperation(value = "分页获取全民运动接口", notes = "分页获取全民运动接口")
    /**
     * number == null查询全部，1查询房间最大人数1个人，2，查询多人房间
     */
    public ResponseEntity<ApiResult> getPaginationAllPeopleSport(long size, long current, Integer type, Integer number, String finishedFlag) {
        Map m = new HashMap<String, Object>();
        m.put("mysize", size);
        m.put("current", (current - 1) * size);
        m.put("userId", securityChecker.getUser().getUserId());
        if (type != null) {
            m.put("type", type);
        }
        m.put("number", number);
        m.put("finishedFlag", finishedFlag);
        List<GetPaginationAllPeopleSport> getPaginationAllPeopleSportList = new ArrayList<>();
        List<RoomUserRelation> roomUserRelationList = roomUserRelationService.getPageRoomMapByUserId(m);
        long count = roomUserRelationService.getCountRoomMapByUserId(m);
        roomUserRelationList.stream().forEach(roomUserRelation -> {
            Room room = roomService.newGetById(roomUserRelation.getRoomId());
            if (room != null) {
                NewSportConfig newSportConfig = roomService.getByType(room.getSportProject());
                GetPaginationAllPeopleSport getPaginationAllPeopleSport = new GetPaginationAllPeopleSport();
                getPaginationAllPeopleSport.setAllDone(roomUserRelation.getAllDone());
                getPaginationAllPeopleSport.setCreateDate(DateUtil.formatDateTimeToStr(room.getCreateDate()));
                getPaginationAllPeopleSport.setFinishedFlag(Integer.parseInt(room.getFinishedFlag()));
                getPaginationAllPeopleSport.setGmtCreate(room.getEndDate());
                getPaginationAllPeopleSport.setPrizeType(room.getPrizeType());
                getPaginationAllPeopleSport.setRoomId(room.getId());
                getPaginationAllPeopleSport.setSportCategoryMainLogo(newSportConfig.getMainLogo());
                getPaginationAllPeopleSport.setSportCategoryName(newSportConfig.getName());
                getPaginationAllPeopleSport.setUserId(securityChecker.getUser().getUserId());
                getPaginationAllPeopleSport.setRoomName(room.getRoomName());
                User user = userService.getUserByUserId(room.getSponsor());
                getPaginationAllPeopleSport.setNickName(user.getNickName());
                getPaginationAllPeopleSport.setPic(user.getPic());
                getPaginationAllPeopleSport.setLogoPic(room.getLogoPic());
                getPaginationAllPeopleSport.setCounter(room.getSportParticipantsCount());
                getPaginationAllPeopleSport.setRoomOwnerId(room.getSponsor());
                QueryWrapper<RoomUserRelation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("room_id", roomUserRelation.getRoomId());
                int joinCounter = roomUserRelationService.count(queryWrapper);
                getPaginationAllPeopleSport.setJoinCounter(joinCounter);
                if (roomUserSportRecordPerDayService.getAllRecordByRoomIdAndUserIdAndDate(roomUserRelation.getUserId(), roomUserRelation.getRoomId(), new Date()) > 0) {
                    getPaginationAllPeopleSport.setTodayDone(1);
                } else {
                    getPaginationAllPeopleSport.setTodayDone(0);
                }
                getPaginationAllPeopleSportList.add(getPaginationAllPeopleSport);
            }
        });
        getPaginationAllPeopleSportList.sort((t1, t2) -> t2.getCreateDate().compareTo(t1.getCreateDate()));
        ApiResult apiResult = new ApiResult();
        Page<GetPaginationAllPeopleSport> paginationAllPeopleSportPage = new Page<>();
        paginationAllPeopleSportPage.setTotal(count);
        paginationAllPeopleSportPage.setRecords(getPaginationAllPeopleSportList);
        paginationAllPeopleSportPage.setCurrent(current);
        paginationAllPeopleSportPage.setSize(size);
        apiResult.setData(paginationAllPeopleSportPage);
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 分钱接口
     */
    @GetMapping("/shareMoney")
    @ApiOperation(value = "分钱接口", notes = "分钱接口")
    public ResponseEntity<ApiResult> shareMoney() {
        //找到所有的活动室id的list, 结束日期是今天的
        Map m = new HashMap<String, Object>();
        //宝箱不在这里处理
        m.put("prizeTypein13", "1");
        //已经结束的活动室不参与分钱
        m.put("finishedFlag", "0");
        List<Room> listRoom = roomService.getRoomList(m);
        List list = null;
        for (Room room : listRoom) {
            long roomId = room.getId();

            if (room.getPrizeType() == 1) {
                double cumulativeDeposit = room.getCumulativeDeposit();

                //if(roomId==186){
                m.put("roomId", roomId);

                //数据库里面直接查询出来有哪些人allDone
                List<Map> roomUserRelationList = roomUserRelationService.getRoomUserRelationAllDoneList(m);

                if (roomUserRelationList.size() > 0) {
                    double shareMoneyAmount = cumulativeDeposit / roomUserRelationList.size();
                    for (Map map : roomUserRelationList) {
                        String userId = map.get("user_id").toString();
                        User user = new User();
                        user.setUserId(userId);

                        //System.out.println("roomId is " + roomId);
                        //分钱给这些人
                        user.setMoney(shareMoneyAmount);
                        userService.updateUser(user);
                    }

                }
                //刷新活动室字段finished为真
                Room roomTemp = new Room();
                roomTemp.setId(roomId);
                roomTemp.setFinishedFlag("1");
                roomService.updateRoom(roomTemp);
                //}
            }


        }
        ApiResult apiResult = new ApiResult();
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 获取活动室用户关联关系详情
     */
    @PostMapping("/getRoomUserRelationDetail")
    @ApiOperation(value = "获取活动室用户关联关系详情", notes = "获取活动室用户关联关系详情")
    public ApiResult getRoomUserRelationDetail(@RequestBody RoomUserRelation roomUserRelation) {
        Map m = new HashMap<String, Object>();
        m.put("id", roomUserRelation.getId());
        m.put("roomId", roomUserRelation.getRoomId());
        m.put("userId", roomUserRelation.getUserId());
        RoomUserRelation roomUserRelationDB = roomUserRelationService.getRoomUserRelationDetail(m);
        //return room;
        ApiResult apiResult = new ApiResult();
        apiResult.setData(roomUserRelationDB);
        return apiResult;
    }

    /**
     * 修改活动室用户关联关系接口
     */
    @PostMapping("/updateRoomUserRelation")
    @ApiOperation(value = "修改活动室用户关联关系接口", notes = "修改活动室用户关联关系接口")
    public ResponseEntity updateRoomUserRelation(@RequestBody RoomUserRelation roomUserRelation) {
        roomUserRelationService.updateRoomUserRelation(roomUserRelation);
//        判断是否房间内所有的人都已经领取宝箱。如果全部领取了就点击房间已经结束
        QueryWrapper<RoomUserRelation> roomUserRelationQueryWrapper01 = new QueryWrapper<>();
        roomUserRelationQueryWrapper01
                .eq("room_id", roomUserRelation.getRoomId())
                .eq("all_done", 1);
        int count01 = roomUserRelationService.count(roomUserRelationQueryWrapper01);
        QueryWrapper<RoomUserRelation> roomUserRelationQueryWrapper02 = new QueryWrapper<>();
        roomUserRelationQueryWrapper02
                .eq("room_id", roomUserRelation.getRoomId())
                .eq("taken_prize", "已领取宝箱");
        int count02 = roomUserRelationService.count(roomUserRelationQueryWrapper02);
        if (count01 == count02) {
            Room room = new Room();
            room.setId(roomUserRelation.getRoomId());
            room.setFinishedFlag("2");
            boolean update = roomService.updateById(room);
        }
        ApiResult apiResult = new ApiResult();
        return ResponseEntity.ok(apiResult);
    }

    /**
     * 获取活动室排行榜第一名和最后一名接口
     */
    @GetMapping("/getStudyPageCount")
    @ApiOperation(value = "获取学习页面参与某个具体项目的人数", notes = "获取学习页面参与某个具体项目的人数")
    public ResponseEntity getStudyPageCount(@RequestParam Long sportProject) {
        ApiResult apiResult = new ApiResult();
        Long size = redisTemplate.opsForSet().size(RedisConstants.StudyPageJoinPerson + sportProject);
        apiResult.setData(size == null ? 0 : size);
        return ResponseEntity.ok(apiResult);
    }

    @Autowired
    private NewSportRecordsService newSportRecordsService;


    /**
     * 根据运动类型查询该用户这新一条运动信息
     */
    @GetMapping("/userNewSportProject")
    @ApiOperation(value = "获取用户最新的运动子类", notes = "获取用户最新的运动子类")
    public ResponseEntity userNewSportProject(Long sportProject, String userId) {

        ApiResult apiResult = new ApiResult();
        try {
            NewSportRecords sportRecord = newSportRecordsService.userNewSportProjectBy(sportProject, userId);

            Map<String, Integer> result = new HashMap<>();
            result.put("type", sportRecord.getType());
            result.put("count", sportRecord.getMeasure().intValue());

            apiResult.setData(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(apiResult);
    }
}